package com.ruoyi.binding.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.binding.domain.JDP.Params.JDPCusQueryOrderParam;
import com.ruoyi.binding.domain.MhBinding;
import com.ruoyi.binding.domain.MhOrderAllocate;
import com.ruoyi.binding.domain.MhUserGamePrice;
import com.ruoyi.binding.service.impl.MhBindingServiceImpl;
import com.ruoyi.binding.service.impl.MhJDPServiceImpl;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.binding.domain.MhOrderInfo;
import com.ruoyi.binding.service.IMhOrderInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 数据汇总Controller
 *
 * @author Ekko
 * @date 2025-06-27
 */
@RestController
@RequestMapping("/order/info")
public class MhOrderInfoController extends BaseController {
    @Autowired
    private IMhOrderInfoService mhOrderInfoService;


    @Autowired
    private MhBindingServiceImpl mhBindingServiceImpl;

    @PreAuthorize("@ss.hasPermi('order:info:list')")
    @GetMapping("/list")
    public TableDataInfo list(MhOrderInfo mhOrderInfo) {
        //查询当前用户id
//        如果是管理员登录，则返回所有数据
        Long userId = SecurityUtils.getUserId();
        if (!mhBindingServiceImpl.selectMhBindingByAdminId(userId).isEmpty()) {
            logger.info("管理员登录，返回所有数据{}", mhBindingServiceImpl.selectMhBindingByAdminId(userId));
            mhOrderInfo.setRecManName(null);
        } else {
            logger.info("普通用户登录，返回当前用户数据{}", mhBindingServiceImpl.selectMhBindingByUserId(userId));
            String acc_name = mhBindingServiceImpl.selectMhBindingByUserId(userId).getSuUserName();
            mhOrderInfo.setRecManName(acc_name);
        }

        startPage();
        List<MhOrderInfo> list = resList(mhOrderInfoService.selectMhOrderInfoList(mhOrderInfo));
        return getDataTable(list);
    }
//    获取游戏类型数组
    @GetMapping("/gameType")
    public List<String> gameType() throws Exception {
        return mhOrderInfoService.getGameType();
    }

    /**
     * 导出数据汇总列表
     */
    @PreAuthorize("@ss.hasPermi('order:info:export')")
    @Log(title = "数据汇总", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MhOrderInfo mhOrderInfo) {
        //查询当前用户id
//        如果是管理员登录，则返回所有数据
        Long userId = SecurityUtils.getUserId();
        if (!mhBindingServiceImpl.selectMhBindingByAdminId(userId).isEmpty()) {
            logger.info("管理员登录，返回所有数据{}", mhBindingServiceImpl.selectMhBindingByAdminId(userId));
            mhOrderInfo.setRecManName(null);
        } else {
            logger.info("普通用户登录，返回当前用户数据{}", mhBindingServiceImpl.selectMhBindingByUserId(userId));
            String acc_name = mhBindingServiceImpl.selectMhBindingByUserId(userId).getSuUserName();
            mhOrderInfo.setRecManName(acc_name);
        }

        List<MhOrderInfo> list = resList(mhOrderInfoService.selectMhOrderInfoList(mhOrderInfo));
        ExcelUtil<MhOrderInfo> util = new ExcelUtil<MhOrderInfo>(MhOrderInfo.class);
        util.exportExcel(response, list, "数据汇总数据");
    }


    //获取当前用户的管理员计算抽成系数后的list
    public List<MhOrderInfo>  resList(List<MhOrderInfo>  oList) {
        // 获取当前用户id
        Long userId = SecurityUtils.getUserId();
        MhBinding mhBinding = mhBindingServiceImpl.selectMhBindingByUserId(userId);

        if (mhBinding == null || mhBinding.getMhUserGamePriceList() == null) {
            logger.warn("用户[{}]未配置游戏比例，跳过价格计算。", userId);
            return oList;
        }

        List<MhUserGamePrice> adminRatioList = mhBinding.getMhUserGamePriceList();

        for (MhOrderInfo o : oList) {
            String gameName = o.getGameName();
            if (gameName == null) {
                logger.warn("订单[{}]无游戏名，跳过。", o.getOrderId());
                continue;
            }

            logger.info("处理订单[{}] 游戏名：{} 原价：{}", o.getOrderId(), gameName, o.getPrice());

            for (MhUserGamePrice priceRatioItem : adminRatioList) {
                String ratioGameName = priceRatioItem.getGameCategoryName();
                if (ratioGameName == null) continue;

                if (ratioGameName.trim().equalsIgnoreCase(gameName.trim())) {
                    BigDecimal originalPrice = o.getPrice();
                    BigDecimal ratio = priceRatioItem.getPriceRatio();
                    if (originalPrice != null && ratio != null) {
                        BigDecimal factor = BigDecimal.ONE.subtract(ratio.divide(BigDecimal.valueOf(100)));
                        BigDecimal finalPrice = originalPrice.multiply(factor).setScale(2, BigDecimal.ROUND_HALF_UP);
                        logger.info("匹配到游戏 [{}]，抽成比例：{}%，计算后价格：{}", ratioGameName, ratio, finalPrice);
                        o.setPrice(finalPrice);
                    }
                    break; // 已匹配到，不需要再循环
                }
            }
        }

        return oList;
    }

    /**
     * 获取数据汇总详细信息
     */
    @PreAuthorize("@ss.hasPermi('order:info:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(mhOrderInfoService.selectMhOrderInfoById(id));
    }

    /**
     * 新增数据汇总
     */
    @PreAuthorize("@ss.hasPermi('order:info:add')")
    @Log(title = "数据汇总", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MhOrderInfo mhOrderInfo) {
        return toAjax(mhOrderInfoService.insertMhOrderInfo(mhOrderInfo));
    }

    /**
     * 修改数据汇总
     */
    @PreAuthorize("@ss.hasPermi('order:info:edit')")
    @Log(title = "数据汇总", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MhOrderInfo mhOrderInfo) {
        return toAjax(mhOrderInfoService.updateMhOrderInfo(mhOrderInfo));
    }

    /**
     * 删除数据汇总
     */
    @PreAuthorize("@ss.hasPermi('order:info:remove')")
    @Log(title = "数据汇总", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(mhOrderInfoService.deleteMhOrderInfoByIds(ids));
    }
}
